package com.hunk.core.web.model;

import java.util.List;
import java.util.Map;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

import com.fasterxml.jackson.annotation.JsonProperty;


/**
 * Description :<br>
 * 
 * @author HunkDeng
 * @since 2013-4-29
 * @param <T>
 */
public class JpaOmGridPage {
	
	/**
	 * Description :<br>
	 * 	OmPage Request With JPA Implement
	 * @author HunkDeng
	 * @since 2013-4-29
	 * @param <T>
	 */
	public static class JpaPageRequest<T> {
		
		private int start;
		
		private int limit;
		
		private Map<String, Object> extraData;
		
		private Sort sort;
		
		public JpaPageRequest(Map<String,Object> params) {
			start = Integer.parseInt((String)params.get("start"));
			limit = Integer.parseInt((String)params.get("limit"));
			extraData = params;
			if (params.get("sortBy") != null && params.get("sortDir") != null) {
				String sortBy = (String) params.get("sortBy");
				Direction sortDir = Sort.Direction.valueOf((String)params.get("sortDir"));
				sort = new Sort(new Sort.Order(sortDir, sortBy));
			}
		}
		
		public JpaPageRequest<T> setSort(Sort sort) {
			this.sort = sort;
			return this;
		}

		public PageRequest getPageRequest() {
			return new PageRequest(start/limit, limit, sort);
		}

		public Map<String, Object> getExtraData() {
			return extraData;
		}
	}
	
	/**
	 * Description :<br>
	 *  OmPage Response With JPA Implement
	 * @author HunkDeng
	 * @since 2013-4-29
	 * @param <T>
	 */
	public static class JpaPageResponse<T> {
		
		private org.springframework.data.domain.Page<T> jpaPage;
		
		public JpaPageResponse(Page<T> jpaPage) {
			super();
			this.jpaPage = jpaPage;
		}		
		@JsonProperty
		public long getTotal() {
			return jpaPage.getTotalElements();
		}
		@JsonProperty
		public List<T> getRows() {
			return jpaPage.getContent();
		}
	}
}
